package Servlet;

import Service.EmailService;
import Service.UserService;
import entity.VerificationCode;
import org.json.JSONException;
import org.json.JSONObject;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author Su
 * @Date 2025/4/30 20:57
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/auth/reset-password")
public class ResetPasswordServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            this.userService = new UserService(connection);
        } catch (SQLException e) {
            throw new ServletException("初始化失败", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");

        JSONObject responseJson = new JSONObject();

        try {
            // 解析请求体里面的json数据
            JSONObject requestJson = parseRequestBody(req);
            // 从JSON中提取邮箱、验证码、新密码和操作类型
            String email = requestJson.getString("email");
            String code = requestJson.getString("code");
            String newPassword = requestJson.getString("newPassword");
            String type = requestJson.getString("type");

            //1、检查验证码是否有效
            VerificationCode resetCode = userService.verifyResetCode(email, code, type);
            if(resetCode == null){
                responseJson.put("code", 400);
                responseJson.put("message", "验证码无效或已过期");
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            // 2、重置密码
            boolean result = userService.resetPassword(email,newPassword);
            if(result){
                responseJson.put("code", 200);
                responseJson.put("message", "密码重置成功");
                resp.setStatus(HttpServletResponse.SC_OK);
            }else {
                responseJson.put("code", 200);
                responseJson.put("message", "密码重置失败");
                resp.setStatus(HttpServletResponse.SC_OK);
            }
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    // 辅助方法：解析请求体为JSON对象
    private JSONObject parseRequestBody(HttpServletRequest req) throws IOException, JSONException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return new JSONObject(sb.toString());
        //******优化，可以像那个welearn那样，有一个密码复杂度校验，大概，ispasswordvalid，在userservice里面添加
    }    //验证码，在verifyresetcode方法中添加
    //if attempts>maxatempts,throw verificationcodeexception 尝试次数过多，请稍后再试






}

